<?php
/*=============================================================================
|| ##################################################################
||	phpFoX Konsort
|| ##################################################################
||
||	Copyright		: (C) 2005-2007 PHPFOX Limited a Reality Fox Creation
||	Contact			: info@phpfox.com
||
||	- phpFoX and all of its source code and files are protected by Copyright Laws.
||
||	- The license for phpFoX permits you to install this software on a single domain (.com, .org, .net, etc.).
||
||	- You may also not remove this copyright screen which shows the copyright information and credits for phpFoX (RealityFOX Creations).
||
||	- phpFoX Konsort is NOT a FREE software - http://www.phpfox.com/license/
||
|| ##################################################################
=============================================================================*/

/* $File: ./include/modules/Admin/classes/PhpFox_ServiceAdmin.class.php, $Author:  $ */



/** Implements some functionality for admin area
 * @package module.admin
 * @version $Id: PhpFox_ServiceAdmin.class.php 337 2008-02-17 13:36:37Z phpfoxsv $
 *
 */
class PhpFox_Mod_Admin_ServiceAdmin extends BaseService
{
    /** Reading content from file
     * @param string $sFile
     * @return string
     */
    function readFromFile($sFile)
    {
        $sOut = '';
        if ($hFile = fopen($sFile, 'r'))
        {
            while (!feof($hFile))
            {
                $sOut .= fread($hFile, 4096);
            }
        }
        return $sOut;
    }

    function getOptions()
    {
    	static $aOptions;

    	if ( $aOptions )
    	{
    		return;
    	}

    	$oReq = &App::getRequest();
		$aItems = array();
		$aOptions = $this->oDatabase->getRows("
			SELECT 
				optionid, url, title 
			FROM ". App::getT('sys_options') ." 
			GROUP BY title
			ORDER BY title
		");
		$sPageName = App::getPage();
		foreach (App::getParam('Mod_Admin.protect_rewrite') as $sKey => $sValue)
		{
			$sPageName = str_replace('.secure_' . $sKey, '', $sPageName);	
		}		
		foreach($aOptions as $aOption)
		{
			$aOption['title'] = ucwords(strtolower(App::format($aOption['title'])));
			if ($sPageName == $aOption['url'])
			{
				$aOption['selected'] = true;
			}
			if ( $aOption['url'] == 'admin.config.core.edit_livecam' && !App::pluginInstalled('chat') )
			{
				continue;
			}
			$aItems[] = $aOption;
		}

		return $aItems;
    }

    /** Writes text into file
     * @param string $sTxt
     * @param string $sFile
     * @return boolean
     */
    function writeToFile($sTxt, $sFile)
    {
        if ($hFile = fopen($sFile, 'w'))
        {
            fwrite($hFile, $sTxt);
            fclose($hFile);
            return true;
        }
        return false;
    }

    /** Checks that file can be edited
     * @param string $sDir
     * @param string $sFile
     * @return boolean
     */
    function file_isset($sDir, $sFile)
    {
        if ((!$sFile) || (!$sDir))
        {
            return false;
        }
        $aAllFiles = array_merge(App::getParam('Mod_Admin.content_pages', 'main'),
                                 App::getParam('Mod_Admin.content_pages', 'email'),
                                 App::getParam('Mod_Admin.content_pages', 'dropdown'));
        foreach ($aAllFiles as $aFile)
        {
            if (($sDir == $aFile['dir']) && ($sFile == $aFile['file']))
            {
                return true;
            }
        }
        return false;
    }

    function getTableStatus()
    {
        $oConfigItem = &$this->_oModule->getItem('Config');
        /* @var $oConfigItem PhpFox_Mod_Admin_ItemConfig */

        return $oConfigItem->oDb->getRows('SHOW TABLE STATUS');
    }

    function optimizeTable($sTable)
    {
        $oConfigItem = &$this->_oModule->getItem('Config');
        /* @var $oConfigItem PhpFox_Mod_Admin_ItemConfig */

        return $oConfigItem->oDb->query('OPTIMIZE TABLE `'.$sTable.'`');
    }

    function repairTable($sTable)
    {
        $oConfigItem = &$this->_oModule->getItem('Config');
        /* @var $oConfigItem PhpFox_Mod_Admin_ItemConfig */

        return $oConfigItem->oDb->query('REPAIR TABLE `'.$sTable.'`');
    }

    /** Returns server statistcs (versions of php, mysql, etc.)
     *
     *
     * @return array server info
     */
    function getServerStats()
    {
        static $aRes = array();

        if (!$aRes)
        {
            //get PHP version
            $aRes['php_version'] = phpversion();

            //get GD version
            if ( function_exists('imagecreatetruecolor') ):
            	$aRes['gd_version'] = '2.x';
            elseif ( function_exists('imagecreate') ):
            	$aRes['gd_version'] = '1.x';
            else:
            	$aRes['gd_version'] = '';
            endif;

            //get safe mode
            $aRes['safe_mode'] = get_cfg_var('safe_mode') ? 'ON' : 'OFF';

            App::loadClass('Database');
            $oDb = &Database::get();
            /* @var $oDb Database */

            //get mysql version
            $aRes['db_version'] = $oDb->getField('SELECT VERSION()');

            //get size
            $iSize = 0;
            $aTables = $oDb->getRows("SHOW TABLE STATUS");
            foreach($aTables as $aTable)
            {
            	$iSize += $aTable["Data_length"] + $aTable["Index_length"];
            }
            $aRes['db_used_space'] = $iSize;

            //get site launch date
            $aRes['start_date'] = App::getSetting('site_launch');

            //get server name
            $aRes['server_name'] = $this->_getWebServer();

            if (!stristr(PHP_OS, "win") AND $sStats = @exec('uptime 2>&1') AND trim($sStats) != '')
			{
				$aStats = explode(",",$sStats);
				if ( isset($aStats[0]) AND isset($aStats[1]) )
				{
					$aInfo = array
					(
						'uptime' => str_replace("up",App::format('server.uptime.term'),$aStats[0]),
						'users' => $aStats[1],
					);

					preg_match("#: ([\d.,]+),?\s+([\d.,]+),?\s+([\d.,]+)$#", $sStats, $aRegs);

					$aRes['server_details'] = $aInfo;
					$aRes['server_load'] = $aRegs;
				}
			}

			$aRes['software_version'] = App::getParam('info.version');
			$aRes['software_build'] = App::getParam('info.build');
			$aQueryCache = $oDb->getRow("SHOW VARIABLES LIKE '%query_cache_size%'");
			$aRes['query_cache'] = App::convert_from_bytes($aQueryCache['Value'], 'MB');
        }

        return $aRes;
    }

    function _getWebServer()
    {
    	define('PHP_SAPI_NAME', php_sapi_name());

        $sWebserver = '';
        $bAddSapi = false;
        if (preg_match('#(Apache)/([0-9\.]+)\s#siU', $_SERVER['SERVER_SOFTWARE'], $wsregs))
        {
        	$sWebserver = "$wsregs[1] v$wsregs[2]";
        	// if (defined('PHP_SAPI_NAME'))
        	{
        	    if (PHP_SAPI_NAME == 'cgi' OR PHP_SAPI_NAME == 'cgi-fcgi')
        	    {
        		    $bAddSapi = true;
        	    }
        	}
        }
        else if (preg_match('#Microsoft-IIS/([0-9\.]+)#siU', $_SERVER['SERVER_SOFTWARE'], $wsregs))
        {
        	$sWebserver = "IIS v$wsregs[1]";
        	$bAddSapi = true;
        }
        else if (preg_match('#Zeus/([0-9\.]+)#siU', $_SERVER['SERVER_SOFTWARE'], $wsregs))
        {
        	$sWebserver = "Zeus v$wsregs[1]";
        	$bAddSapi = true;
        }
        else if (strtoupper($_SERVER['SERVER_SOFTWARE']) == 'APACHE')
        {
        	$sWebserver = 'Apache';
        	// if (defined('SAPI_NAME'))
        	{
            	if (PHP_SAPI_NAME == 'cgi' OR PHP_SAPI_NAME == 'cgi-fcgi')
            	{
            		$bAddSapi = true;
            	}
        	}
        }
        else
        {
        	$sWebserver = PHP_SAPI_NAME;
        }

        if ($bAddSapi)
        {
            // if (defined('PHP_SAPI_NAME'))
        	{
        	   $sWebserver .= ' (' . PHP_SAPI_NAME . ')';
        	}
        }

        return $sWebserver;
    }

    /** Performs site checks
     *
     *
     * @return array site warning or empty array if no warnings found
     */
    function getSiteWarnings($sPurgeUserUrl='')
    {
    	if ( isset($_COOKIE['phpfox_no_warning']) )
    	{
    		return '';
    	}

        $aWarnings = array();

        //check install folder
        if (file_exists(App::getParam('path').'install'))
        {
            $aWarnings[] = App::format('admin.remove.setup');
        }

        if ( !extension_loaded('curl') )
        {
        	$aWarnings[] = App::format('Mod_Admin.no_curl');
        }

        if (App::hasModule('Music'))
        {
        	$aErrors = array();

        	$iSize = App::getParam('Mod_Music.max_song_size');

     	   if (!ini_get('file_uploads'))
     	   {
     	       $aErrors[] = array(
     	       	'name' => 'file_uploads',
     	       	'setting' => 'true',
     	       	'fail' => ini_get('file_uploads'),
     	       	);
     	   }

     	   $iPostMaxSize = App::_size2Byte(ini_get('post_max_size'));
     	   if ($iSize > $iPostMaxSize)
     	   {
     	       $aErrors[] = array(
     	       	'name' => 'post_max_size',
     	       	'setting' => App::convert_from_bytes($iSize,"MB") . 'M',
     	       	'fail' => ini_get('post_max_size'),
     	       	);
     	   }

	       $iUploadMaxFileSize = App::_size2Byte(ini_get('upload_max_filesize'));
	       if ($iSize > $iUploadMaxFileSize)
	       {
     	       $aErrors[] = array(
     	       	'name' => 'upload_max_filesize',
     	       	'setting' => App::convert_from_bytes($iSize,"MB") . 'M',
     	       	'fail' => ini_get('upload_max_filesize'),
     	       	);
	       }

	       $iMaxInputTime = ini_get('max_input_time');
	       if (($iMaxInputTime < 600) && ($iMaxInputTime != '-1'))
	       {
     	       $aErrors[] = array(
     	       	'name' => 'max_input_time',
     	       	'setting' => '-1',
     	       	'fail' => ini_get('max_input_time'),
     	       	);
	       }

           if ( count($aErrors) > 0 )
           {
	           	$sInfo = "<ul>";
            	foreach($aErrors as $error)
            	{
            		$sInfo .= '<li>'. App::format('core.php.setting',array($error['name'],$error['setting'],$error['fail'])) .'</li>';
            	}
            	$sInfo .= "</ul>";

                $aWarnings[] = App::format('music.fail',$sInfo);
			}

            if (file_exists(App::getParam('path').'site/public/music.php'))
            {
                $aWarnings[] = App::format('Mod_Admin.errors.music_file_exists');
            }
            
            $oDb =& Database::get();            

        	$aPluginTotals['mp3_songs'] = ($this->_isTable('phpfox_media') ? $oDb->getField("SELECT COUNT(*) FROM phpfox_media " . ($this->_checkField('phpfox_media', 'is_imported') ? " WHERE is_imported != 1" : "")) : 0);
			$aPluginTotals['music_videos'] = ($this->_isTable('music') ? $oDb->getField("SELECT COUNT(*) FROM music " . ($this->_checkField('music', 'is_imported') ? " WHERE is_imported != 1" : "")) : 0);
			$aPluginTotals['videos'] = ($this->_isTable('php_videos') ? $oDb->getField("SELECT COUNT(*) FROM php_videos " . ($this->_checkField('php_videos', 'is_imported') ? " WHERE is_imported != 1" : "")) : 0);
			$aPluginTotals['editor'] = ($this->_isTable('phpfox_editor') ? $oDb->getField("SELECT COUNT(*) FROM phpfox_editor " . ($this->_checkField('phpfox_editor', 'is_imported') ? " WHERE is_imported != 1" : "")) : 0);
			$aPluginTotals['total'] = ($aPluginTotals['mp3_songs'] + $aPluginTotals['music_videos'] + $aPluginTotals['videos'] + $aPluginTotals['editor']);
			if ($aPluginTotals['total']) 
			{
				$aWarnings[] = App::format('Mod_Admin.plugin_import', array(App::makeUrl('admin.extra.musicmod-update')));
			}
        }

        return $aWarnings;
    }
    
	function _isTable($sTable)		
	{
		return $this->oDatabase->getRows("SHOW TABLES LIKE '". $sTable ."'");	
	}    
	
    function _checkField($sTable, $sVar)
    {
    	$aCheckOptions = $this->oDatabase->getRows("SHOW COLUMNS FROM `" . $sTable . "`");
		foreach($aCheckOptions as $aLangOption)
		{
			if ( $aLangOption['Field'] == $sVar )
			{
				return true;
			}
		}
		return false;
    }	

    /** Get site statistics for today
     *
     *
     * @return array site stats for today
     */
    function getTodayStats()
    {
        $aStats = array();

        App::loadClass('Database');
        $oDb = &Database::get();
        /* @var $oDb Database */

        $iToday = mktime(0,0,0, date('m'), date('d'), date('Y'));

        App::getModule('Account');
        $aStats['new_members'] = $oDb->getField('SELECT COUNT(*) FROM '.App::getT('user').
                                                '  WHERE signup >= "'.$oDb->date().'"');

        $aStats['new_members']       = $this->_getTodayInfo('Account', 'user', '', 'signup');
        $aStats['new_comments']      = $this->_getTodayInfo('Comments', 'comments');
        $aStats['new_images']        = $this->_getTodayInfo('Gallery', 'main');
        $aStats['rated_images']      = $this->_getTodayInfo('Gallery', 'rating');
        $aStats['new_polls']         = $this->_getTodayInfo('Poll', 'polls');
        $aStats['voted_polls']       = $this->_getTodayInfo('Poll', 'poll_vote');
        $aStats['new_quizzes']       = $this->_getTodayInfo('Quiz', 'hot_quiz');
        $aStats['new_forum_topic']   = $this->_getTodayInfo('Forum', 'forum_topic');
        $aStats['new_fourm_replies'] = $this->_getTodayInfo('Forum', 'forum_reply');
        $aStats['new_blogs']         = $this->_getTodayInfo('Blog', 'journal');
        $aStats['new_messages']      = $this->_getTodayInfo('Messenger', 'mail', ' AND `type` = "mail"');
        $aStats['new_crushes']       = $this->_getTodayInfo('Messenger', 'mail', ' AND `type` = "crush"');
        $aStats['new_videos'] = $oDb->getField('SELECT COUNT(*) FROM `'.App::getT('videos').'` WHERE `vid_time` >= '.$iToday.'');
        $aStats['new_songs'] = $oDb->getField('SELECT COUNT(*) FROM `'.App::getT('music_song').'` WHERE UNIX_TIMESTAMP(song_cdate) >= "'. $iToday .'"');

        return $aStats;
    }

    function _getTodayInfo($sModule, $sTable, $sCond = '', $sField='time')
    {
        App::getModule($sModule);
        $iToday = mktime(0,0,0, date('m'), date('d'), date('Y'));
    	$oDb = &Database::get();
    	return $oDb->getField('SELECT COUNT(*) FROM `'.App::getT($sTable).'` WHERE `'.$sField.'` >= '.$iToday.$sCond);
    }

    /**
     * Saves
     *
     * @param unknown_type $sCode
     * @param unknown_type $sValue
     */
    function saveSetting($sCode, $sValue)
    {
        $oConfigItm = &$this->_oModule->getItem('Config');
        $oConfigItm->oDb->update(App::getT('sys_sett'), array('val' => $sValue), 'code = "' . $oConfigItm->oDb->escape($sCode) . '"');
    }

}
?>